/**
 * 优先级队列元素
 */
export class QueueElement<T> {
  /** 队列中的元素 */
  element: T
  /** 队列中元素的优先级  */
  priority: number
  // 构造函数，用于初始化QueueElement对象
  constructor(element: T, priority: number) {
    // 将传入的element参数赋值给element变量
    this.element = element
    // 将传入的priority参数赋值给priority变量
    this.priority = priority
  }
}

/**
 * @author hzq
 * @description 优先级队列
 * @date 2024-11-03
 */
class PriorityQueue<T> {
  private items: QueueElement<T>[] = []

  enqueue(element: T, priority: number) {
    const queueElement = new QueueElement(element, priority)
    if (this.items.length === 0) {
      this.items.push(queueElement)
    } else {
      let isAdded = false
      for (let i = 0; i < this.items.length; i++) {
        if (queueElement.priority < this.items[i].priority) {
          this.items.splice(i, 0, queueElement)
          isAdded = true
          break
        }
      }
      if (!isAdded) {
        this.items.push(queueElement)
      }
    }
  }

  dequeue() {
    return this.items.shift()
  }

  front() {
    return this.items[0]
  }

  isEmpty() {
    return this.items.length === 0
  }

  get size() {
    return this.items.length
  }
}

export default PriorityQueue
